package com.hjx.movie.core.system.service.commons.file;

import com.hjx.movie.common.utils.ResultType;
import com.hjx.movie.common.utils.exceptions.CustomException;
import com.hjx.movie.core.system.runner.SystemStaticData;
import com.hjx.movie.core.system.vo.FileVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Title:</p>
 * <p>Description:</p>
 *
 * @author hjx
 * @date 2020/6/19 - 15:14
 */
@Slf4j
@Service
public class FileService {
    @Value("${file.disk}")
    private String disk;

    @Value("${file.path}")
    private String path;

    @Resource
    private SystemStaticData staticData;

    public static String fileUpload(MultipartFile multipartFile, String realPath){
        String originalFilename = multipartFile.getOriginalFilename();
        Assert.notNull(originalFilename,"原始文件名不能为空");
        String[] s = originalFilename.split("\\.");
        if (StringUtils.isBlank(realPath)){
            log.error("文件上传失败,真实上传路径为空");
            throw new CustomException(ResultType.USER_INPUT_ERROR,"文件上传失败,真实上传路径为空");
        }
//        String realPath = request.getServletContext().getRealPath("/upload");
        File file = new File(realPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        String realName = System.currentTimeMillis()+"."+s[s.length-1];
        String targetPath = realPath +File.separator+ realName;
        try {
            multipartFile.transferTo(new File(targetPath));
            log.debug("文件上传成功");
        } catch (IOException e) {
            log.error("文件上传失败,{}",e.getMessage());
            e.printStackTrace();
            throw new CustomException(ResultType.USER_INPUT_ERROR,"文件上传失败");
        }
        return realName;

    }


    public String getBaseResHttpUrl(String paramKey){
        if (StringUtils.isNotBlank(paramKey)){
            return staticData.getStaticValue(paramKey);
        }else {
            log.error("请输入静态参数的Key值");
            throw new CustomException(ResultType.SYSTEM_ERROR,"请输入静态参数的Key值");
        }
    }

    public List<FileVo> getResFileList(Long id, String realPath,String paramKey){
        log.debug("获取资源文件列表");
        String baseUrl = getBaseResHttpUrl(paramKey);
        File file = new File(realPath);
        List<FileVo> fileVoList = new ArrayList<>();
        String[] fileList = file.list();
        if (fileList==null||fileList.length==0){
            log.debug("返回空资源文件列表");
            return fileVoList;
        }
        int i = 0;
        for (String name:fileList){
            i--;
            String url = baseUrl+id+"/"+name;
            FileVo fileVo = new FileVo(i,name,"done",url,url);
            fileVoList.add(fileVo);
        }
        log.debug("返回资源文件列表");
        return fileVoList;
    }


    public static boolean deleteRes(String fileName, String realPath) {
        String pathName = realPath+File.separator+fileName;
        log.debug("删除资源文件:{}",pathName);
        try {
            File file = new File(pathName);
            return file.delete();
        }catch (Exception e){
            log.error("删除资源文件失败,{}",pathName);
            e.printStackTrace();
            return false;
        }
    }

    public String getRealPath(Long id,String folderKey){
        String realPath = "";
        if (StringUtils.isNotBlank(folderKey)){
            realPath = disk+File.separator+path+File.separator+ staticData.getStaticValue(folderKey) +File.separator+id;
            log.debug("获取真实路径:{}",realPath);
            return realPath;
        }else {
            log.error("获取真实路径失败");
            throw new CustomException(ResultType.USER_INPUT_ERROR,"获取真实路径失败");
        }
    }

    public static void fileMultiUpload(List<MultipartFile> multipartFileList,String realPath){
        log.debug("开始处理多文件上传");
        for (MultipartFile file:multipartFileList){
            fileUpload(file,realPath);
        }
        log.debug("多文件上传处理结束");
    }


    /*
     * 根据浏览器的不同进行编码设置，返回编码后的文件名
     */
    public static String getFileName(HttpServletRequest request, String fileName) throws Exception {
        // IE不同版本User-Agent中出现的关键词
        String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
        // 获取请求头代理信息
        String userAgent = request.getHeader("User-Agent");
        for (String keyWord : IEBrowserKeyWords) {
            if (userAgent.contains(keyWord)) {
                //IE内核浏览器，统一为UTF-8编码显示
                return URLEncoder.encode(fileName, "UTF-8");
            }
        }
        //火狐等其它浏览器
        return new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
    }
}
